package fw.communication.coap;

import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapObserveRelation;
import org.eclipse.californium.core.coap.MediaTypeRegistry;

import fw.communication.api.ICommunicationLayer;
import fw.communication.api.IResponseSubscriber;
import fw.communication.api.ProtocolDataMessage;

/**
 * CoapCommunicationLayer is an impelemntation of the communication layer for COAP
 * 
 * @author Andrei Penchev
 *
 */
public class CoapCommunicationLayer implements ICommunicationLayer {

	private String coapHost = "";
	private String coapClient = "";
	private CoapClient client;
	private IResponseSubscriber resSubsriber;
	
	public boolean initialiazeClient(String uri) {
			client = new CoapClient("coap://"
					+ coapHost + ":"
					+ coapClient + uri);
			return true;
	}
	
	/**
	 * @see fw.communication.api.ICommunicationLayer#sendMessage(fw.communication.api.ProtocolDataMessage)
	 */
	public boolean sendMessage(ProtocolDataMessage message) {
        if (client != null) {
            int format = MediaTypeRegistry.parse(message.getContentType());
            client.post(message.getMessageData(), format);
            return true;
        }
        else {
            return false;
        }
    }

	/**
	 * @see fw.communication.api.ICommunicationLayer#setSubscriber(fw.communication.api.IResponseSubscriber)
	 */
	public void setSubscriber(IResponseSubscriber resSubsriber) {
		this.resSubsriber = resSubsriber;
	}
	
	/**
	 * @see fw.communication.api.ICommunicationLayer#receiveMessage(fw.communication.api.ProtocolDataMessage)
	 */
	public void receiveMessage(ProtocolDataMessage message) {
		if(resSubsriber != null) {
			resSubsriber.messageReceived(message);
		}
	}
	
	public boolean subscribe(String uri, String contentType) {
		if (client != null) {
			int accept = MediaTypeRegistry.parse(contentType);
			CoapObserveRelation relation = client.observe(
					new CoapResponseHandlerImpl(this), accept);
			return true;
		} else {
			return false;
		}
	}
}
